//
//  AlbumPickerController.m
//
//  Created by Matt Tuzzolo on 2/15/11.
//  Copyright 2011 ELC Technologies. All rights reserved.
//

#import "ELCAlbumPickerController.h"
#import "ELCImagePickerController.h"
#import "ELCAssetTablePicker.h"
#import "SelectedCell.h"

@implementation ELCAlbumPickerController

@synthesize parent, assetGroups;
@synthesize sourceType = _sourceType;
@synthesize albumSelectArray = _albumSelectArray;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil type:(NSInteger)type
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
	{
		self.sourceType = type;
        _isEditState = NO;
	}
	
	return self;
}

- (void)becomeEditState
{
    if(_isEditState == NO)
    {
        self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", @"") 
                                                                                   style:UIBarButtonItemStyleDone
                                                                                  target:self
                                                                                  action:@selector(becomeEditState)] autorelease];
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Import", @"") 
                                                                                   style:UIBarButtonItemStyleBordered
                                                                                  target:self
                                                                                  action:@selector(ExportAlbum)] autorelease];
        [self.navigationItem setTitle:NSLocalizedString(@"Select Album", @"")];
    }
    else
    {
        self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Cancel", @"")
                                                                                  style:UIBarButtonItemStyleDone
                                                                                 target:self.parent
                                                                                 action:@selector(cancelImagePicker)] autorelease];
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Edit", @"") 
                                                                                   style:UIBarButtonItemStyleBordered
                                                                                  target:self
                                                                                  action:@selector(becomeEditState)] autorelease];
        [self.navigationItem setTitle:NSLocalizedString(@"Album Library", @"")];
    }
    
    _isEditState = !_isEditState;
    [self.tableView reloadData];
}

- (void)ExportAlbum
{
    if(_albumSelectArray == nil)
    {
        self.albumSelectArray = [NSMutableArray array];
    }
    else
    {
        [_albumSelectArray removeAllObjects];
    }
    
    _photoCount = 0;
    
    NSInteger albumCount = [assetGroups count];
    
    for (NSInteger assetIndex = 0; assetIndex < albumCount; assetIndex++) 
	{
		SelectedCell *albumCell = (SelectedCell*)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:assetIndex inSection:0]];
		if(albumCell.isSelected)
		{
            ALAssetsGroup* assetsGroup = [assetGroups objectAtIndex:assetIndex];
			[_albumSelectArray addObject:assetsGroup];
            _photoCount += [assetsGroup numberOfAssets];
		}
	}
    
    if([_albumSelectArray count] == 0)
    {
        UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:nil
															 message:NSLocalizedString(@"Please Select Album", @"") 
															delegate:nil
												   cancelButtonTitle:NSLocalizedString(@"Ok", @"")
												   otherButtonTitles:nil] autorelease];
		[alertView show];
		return;
    }
    else
    {
        [self.parent savePhotosAssets:_albumSelectArray];
    }
}

#pragma mark -
#pragma mark View lifecycle


- (void)getAlbumInfo
{
    [self.navigationItem setTitle:NSLocalizedString(@"Loading....", @"")];
    
    // Load Albums into assetGroups
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                       
                       // Group enumerator Block
                       void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) 
                       {
                           if (group == nil) 
                           {
                               return;
                           }
                           
                           if(_sourceType == kSourceVideo)
                           {
                               [group setAssetsFilter:[ALAssetsFilter allVideos]];
                           }
                           else
                           {
                               [group setAssetsFilter:[ALAssetsFilter allPhotos]];
                           }
                           
                           if([group numberOfAssets] == 0)
                           {
                               ;
                           }
                           else
                           {
                               [self.assetGroups addObject:group];
                           }
                           
                           // Reload albums
                           [self performSelectorOnMainThread:@selector(reloadTableView) withObject:nil waitUntilDone:YES];
                       };
                       
                       // Group Enumerator Failure Block
                       void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
                           
                           UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Location Error", @"") message:NSLocalizedString(@"Location Must be open", @"") delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                           [alert show];
                           [alert release];
                           
                           NSLog(@"A problem occured %@", [error description]);	                                 
                       };	
                       
                       // Enumerate Albums       
                       [library enumerateGroupsWithTypes:ALAssetsGroupAll
                                              usingBlock:assetGroupEnumerator 
                                            failureBlock:assetGroupEnumberatorFailure];
                       
                       [pool release];
                   }); 
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Cancel", @"")
                                                                              style:UIBarButtonItemStyleDone 
                                                                             target:self.parent
                                                                             action:@selector(cancelImagePicker)] autorelease];
    
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
	self.assetGroups = tempArray;
    [tempArray release];
    
    library = [[ALAssetsLibrary alloc] init];   
    [self getAlbumInfo];
    
}

-(void)reloadTableView {
	
	[self.tableView reloadData];
	[self.navigationItem setTitle:NSLocalizedString(@"Album Library", @"")];
    if([assetGroups count] != 0)
    {
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Edit", @"") 
                                                                                   style:UIBarButtonItemStyleBordered
                                                                                  target:self
                                                                                  action:@selector(becomeEditState)] autorelease];
    }
    else
    {
        if([assetGroups count] == 0)
        {
            self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(getAlbumInfo)] autorelease];
            
            if(_sourceType == kSourceVideo)
            {
                [self.navigationItem setTitle:NSLocalizedString(@"NO Video", @"")];
            }
            else
            {
                [self.navigationItem setTitle:NSLocalizedString(@"NO Photo", @"")];
            }
        }
    }
}

-(void)selectedAssets:(NSArray*)_assets {
	
	[(ELCImagePickerController*)parent selectedAssets:_assets];
}

- (void)saveSelectdPhotoDirectly:(NSArray*)assetArray
{
    [(ELCImagePickerController*)parent saveSelectdPhotoDirectly:assetArray];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [assetGroups count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    SelectedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[SelectedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    

    
    // Get count
    ALAssetsGroup *g = (ALAssetsGroup*)[assetGroups objectAtIndex:indexPath.row];
    
    NSInteger gCount = [g numberOfAssets];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ (%d)",[g valueForProperty:ALAssetsGroupPropertyName], gCount];
    
    //NSEnumerationReverse
    [g enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) 
     {         
         if(result == nil) 
         {
             return;
         }
         
         [cell.imageView setImage:[UIImage imageWithCGImage:[result thumbnail]]];
         *stop = YES;
     }]; 
    
    if(_isEditState == NO)
    {
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        cell.backgroundView = nil;
        cell.isSelected = NO;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"unselectedBackground.png"]] autorelease];
    }
    

	
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if(_isEditState)
    {
        SelectedCell *newCell = (SelectedCell*)[tableView cellForRowAtIndexPath:indexPath];
        newCell.isSelected = !newCell.isSelected;
        
        //使该行不保持突出显示
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    
	ELCAssetTablePicker *picker = [[ELCAssetTablePicker alloc] initWithNibName:@"ELCAssetTablePicker" bundle:[NSBundle mainBundle]];
	picker.parent = self;

    // Move me    
    picker.assetGroup = [assetGroups objectAtIndex:indexPath.row];
    if(_sourceType == kSourceVideo)
    {
        [picker.assetGroup setAssetsFilter:[ALAssetsFilter allVideos]];
    }
    else
    {
        [picker.assetGroup setAssetsFilter:[ALAssetsFilter allPhotos]];
    }
    
	[self.navigationController pushViewController:picker animated:YES];
	[picker release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 57;
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc 
{	
	[assetGroups release];
    [library release];
    [_albumSelectArray release];
    [super dealloc];
}


@end

